<?php

/**
 *   OPENSHOP 供应商系列管理
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: supplier_manage.php,v 1.0 2009/07/13 09:36:58 created $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);
require(dirname(__FILE__) . '/includes/init.php');

$action    = isset($_REQUEST['act']) ? $_REQUEST['act'] : 'list';
$exc       = new exchange($os->table('supplier'), $db, 'supplier_id', 'supplier_name');
$exc_type  = new exchange($os->table('supplier_type'), $db, 'supplier_type_id', 'supplier_type_name');
$exc_goods = new exchange($os->table('supplier_goods'), $db, 'supplier_goods_id', 'goods_brief'); 

/*------------------------------------------------------ */
//-- 供应商列表
/*------------------------------------------------------ */
if($_REQUEST['act']=='list'){
	
    /* 检查权限 */
    admin_priv();  
  
    $smarty->assign('ur_here',      '供应商列表');    
	$smarty->assign('action_link',  array('text' => '添加供应商', 'href' => 'supplier_manage.php?act=add'));    
    $smarty->assign('full_page',    1);
   
    $list = get_supplier_list();  
    $smarty->assign('supplier_list', $list['supplier']);    
    $smarty->assign('supplier_type_list', supplier_type_list(0));
    $smarty->assign('filter',        $list['filter']);
    $smarty->assign('page_count',    $list['page_count']); 
    $smarty->assign('record_count',  $list['record_count']);
    
    assign_query_info();
    $smarty->display('supplier_list.tpl');	
}
/*------------------------------------------------------ */
//-- 供应商翻页，排序
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='query'){
	
    $list = get_supplier_list();
    $smarty->assign('supplier_list',  $list['supplier']);
    $smarty->assign('filter',         $list['filter']);
    $smarty->assign('record_count',   $list['record_count']);
    $smarty->assign('page_count',     $list['page_count']);
    
    make_json_result($smarty->fetch('supplier_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}
/*------------------------------------------------------ */
//-- 添加、编辑供应商
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_supplier' : 'edit_supplier';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert' : 'update');

    /* 初始化、取得供应商信息 */
    if ($is_add)
    {
        $supplier = array(
            'supplier_id'     		=> 0,
            'supplier_code'   		=> '',
            'supplier_type'   		=> 0,        
            'supplier_name'   		=> '',
            'is_balance'      		=> 1,
            'supplier_desc'   		=> '',
            'address'        		=> '',
            'linkman'         		=> '',
            'principal'       		=> '',
            'zipcode'         		=> '',
            'office_phone'    		=> '',
            'mobile_phone'    		=> '',
            'fax'             		=> '',
            'email'           		=> '',
			'website'      	  		=> '',        
			'bank_name'       		=> '',   
			'bank_account'    		=> '',   
			'tax_no'      	  		=> '',   
			'legal_person'    		=> '',   
			'supply_discount' 		=> 1,   
			'supply_type'     		=> 0,   
			'balance_type'    		=> 0, 
			'balance_date'   	    => local_date('d'), 
			'finance_desc'    		=> '', 
            'supply_discount' 		=> 1
        );
        
        /* 经营商品 */
        $supplier_goods_list = array();
        $sql = "DELETE FROM " . $os->table('supplier_goods') .
                " WHERE supplier_id=0 AND admin_id='$_SESSION[admin_id]'";
        $db->query($sql);
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id  = intval($_GET['id']);
        $sql = "SELECT * FROM " . $os->table('supplier') . " WHERE supplier_id='$id'";
        $supplier = $db->getRow($sql);
        if (empty($supplier))
        {
            sys_msg('供应商不存在');
        }
        $supplier_goods_list   = get_supplier_goods($supplier['supplier_id']);  // 经营商品
    }
    
    $smarty->assign('supplier_type_list',  supplier_type_list($supplier['supplier_type'], $is_add)); // 取得供应商类型
    $smarty->assign('cat_list',     cat_list(0, $cat_id));
    $smarty->assign('brand_list',   get_brand_list());
    $smarty->assign('supplier_goods_list', $supplier_goods_list);
    
    $smarty->assign('supplier', $supplier);


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加供应商');
    }
    else
    {
        $smarty->assign('ur_here', '编辑供应商');
    }
    if ($is_add)
    {
        $href = 'supplier_manage.php?act=list';
    }
    else
    {
        $href = 'supplier_manage.php?act=list';
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '供应商列表'));
    
    assign_query_info();
    
    $smarty->display('supplier_info.tpl');     
}
/*------------------------------------------------------ */
//-- 提交添加、编辑供应商
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_supplier' : 'edit_supplier';
    admin_priv($priv_str);

    /* 提交值 */
    $supplier = array(
        'supplier_id'     			=> intval($_POST['id']),
        'supplier_code'   			=> sub_str($_POST['supplier_code'], 20, false),
		'supplier_type'   			=> !empty($_POST['supplier_type']) ? intval($_POST['supplier_type']) : 0,        
		'supplier_name'   			=> sub_str($_POST['supplier_name'], 80, false),
		'is_balance'      			=> !empty($_POST['is_balance']) ? intval($_POST['is_balance']) : 0,
		'supplier_desc'   			=> strval($_POST['supplier_desc']),
		'address'         			=> sub_str($_POST['address'], 120, false),
		'linkman'         			=> strval($_POST['linkman']),
		'principal'       			=> strval($_POST['principal']),
		'zipcode'         			=> strval($_POST['zipcode']),
		'office_phone'    			=> strval($_POST['office_phone']),
		'mobile_phone'    			=> strval($_POST['mobile_phone']),
		'fax'             			=> strval($_POST['fax']),
		'email'           			=> strval($_POST['email']),
		'website'      	  			=> strval($_POST['website']),        
		'bank_name'       			=> strval($_POST['bank_name']),   
		'bank_account'    			=> strval($_POST['bank_account']),   
		'tax_no'      	  			=> strval($_POST['tax_no']),   
		'legal_person'    			=> strval($_POST['legal_person']),   
		'supply_discount' 			=> floatval($_POST['supply_discount']),   
		'supply_type'     			=> intval($_POST['supply_type']),   
		'balance_type'    			=> intval($_POST['balance_type']), 
		'balance_date'       	    => sub_str($_POST['balance_date'], 80, false), 
		'finance_desc'      	  	=> strval($_POST['finance_desc']), 
		'supplier_status'      	  	=> intval($_POST['supplier_status'])  
    );
    
    /* 判断名称是否重复 */
    if (!$exc->is_only('supplier_name', $supplier['supplier_name'], $supplier['supplier_id']))
    {
        sys_msg('该供应商名称已存在，请您换一个名称');
    }
    
    if (!$exc->is_only('supplier_code', $supplier['supplier_code'], $supplier['supplier_id']))
    {
        sys_msg('该供应商代码已存在，请您换一个代码');
    }
    /* 保存供应商类型信息 */
    if ($is_add)
    {
        $db->autoExecute($os->table('supplier'), $supplier, 'INSERT');
        $supplier['supplier_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('supplier'), $supplier, 'UPDATE', "supplier_id = '$supplier[supplier_id]'");
    }
   
    if ($is_add)
    {
    	handle_supplier_goods($supplier['supplier_id']);
    }
    /* 记日志 */
    if ($is_add)
    {
        admin_log($supplier['supplier_name'], 'add', 'supplier');
    }
    else
    {
        admin_log($supplier['supplier_name'], 'edit', 'supplier');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'supplier_manage.php?act=add', 'text' => '继续添加新的供应商'),
            array('href' => 'supplier_manage.php?act=list', 'text' => '返回供应商列表')
        );
        sys_msg('添加供应商成功', 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'supplier_manage.php?act=list', 'text' => '返回供应商列表')
        );
        sys_msg('编辑供应商成功', 0, $links);
    }	
}
/*------------------------------------------------------ */
//-- 删除供应商
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='remove'){
	
    check_authz_json('drop_supplier');

    $sup_id = intval($_GET['id']);
    $sup_name = $db->getOne("SELECT supplier_name FROM " . $os->table('supplier') . " WHERE supplier_id='$sup_id'");    
    if($db->query("DELETE FROM " . $os->table('supplier') . " WHERE supplier_id='$sup_id'")){
	    /* 记日志 */
	    admin_log($sup_name, 'remove', 'supplier');	
	    $db->query("DELETE FROM " . $os->table('supplier_goods') . " WHERE supplier_id='$sup_id'");
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'supplier_manage.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;	
}
/*------------------------------------------------------ */
//-- 批量操作供应商
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch')
{
    /* 检查权限 */
    admin_priv('drop_supplier');
    
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
    {
        sys_msg('没有选择记录');
    }
    else
    {
        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            /* 删除记录 */
            $sql = "DELETE FROM " . $os->table('supplier') . " WHERE supplier_id " . db_create_in($ids);
            $db->query($sql);

            /* 记日志 */
            admin_log('', 'batch_remove', 'supplier');
			$db->query("DELETE FROM " . $os->table('supplier_goods') . " WHERE supplier_id " . db_create_in($ids));
			
            /* 清除缓存 */
            clear_cache_files();

            sys_msg('批量删除供应商成功');
        }
    }
}
/*------------------------------------------------------ */
//-- 获取供应商经营商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_goods_list'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] =  array('value' => $val['goods_id'],
						'text'  => $val['goods_name'] . ' -- [' . $val['goods_sn'] . ']',
						'data'  => $val['shop_price']);
    }

    make_json_result($opt);
}
/*------------------------------------------------------ */
//-- 添加供应商经营商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_supplier_goods'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

//    check_authz_json('goods_manage');

    $fittings      = $json->decode($_GET['add_ids']);
    $arguments     = $json->decode($_GET['JSON']);
    $supplier_id   = intval($arguments[0]);
    $price         = floatval($arguments[1]);
    $goods_brief   = !empty($arguments[2]) ? sub_str(trim($arguments[2]), 1000, false) : '';
    foreach ($fittings AS $val)
    {
    	if(empty($arguments[1]) || !is_numeric($arguments[1])){ 
    		$price = $db->getOne("SELECT shop_price FROM " . $os->table('goods') . " WHERE is_delete=0 AND goods_id='$val'");
    	}
        $sql = "INSERT INTO " . $os->table('supplier_goods') . " (supplier_id, goods_id, purchase_price, goods_brief, " .
               "admin_id) VALUES ('$supplier_id', '$val', '$price', '$goods_brief', '$_SESSION[admin_id]')";
        $db->query($sql, 'SILENT');
    }

    $arr = get_supplier_goods($supplier_id);
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['goods_id'],
                        'text'      => $val['goods_name'],
                        'data'      => '');
    }

    clear_cache_files();
    make_json_result($opt);
}
/*------------------------------------------------------ */
//-- 删除供应商经营商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_supplier_goods'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

//    check_authz_json('goods_manage');

    $fittings      = $json->decode($_GET['drop_ids']);
    $arguments     = $json->decode($_GET['JSON']);
    $supplier_id   = intval($arguments[0]);
    $price         = floatval($arguments[1]);

    $sql = "DELETE FROM " .$os->table('supplier_goods') .
            " WHERE supplier_id='$supplier_id' AND " .db_create_in($fittings, 'goods_id');
    if ($supplier_id == 0)
    {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $arr = get_supplier_goods($supplier_id);
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] =  array('value'      => $val['goods_id'],
                        'text'      => $val['goods_name'],
                        'data'      => '');
    }

    clear_cache_files();
    make_json_result($opt);
}
/*------------------------------------------------------ */
//-- 供应商类型列表
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='list_type'){
	
    /* 检查权限 */
    admin_priv();  
  
    $smarty->assign('ur_here',      '供应商类型列表');    
	$smarty->assign('action_link',  array('text' => '添加供应商类型', 'href' => 'supplier_manage.php?act=add_type'));    
    $smarty->assign('full_page',    1);
    
    $list = get_supplier_type_list();  
    $smarty->assign('supplier_type_list',     $list['type']);    
    $smarty->assign('filter',                 $list['filter']);
    $smarty->assign('page_count',             $list['page_count']); 
    $smarty->assign('record_count',           $list['record_count']);
    
    assign_query_info();
    
    $smarty->display('supplier_type_list.tpl');
}
/*------------------------------------------------------ */
//-- 供应商类型翻页，排序
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='query_type'){	
    $list = get_supplier_type_list();
    $smarty->assign('supplier_type_list',   $list['type']);
    $smarty->assign('filter',               $list['filter']);
    $smarty->assign('record_count',    		$list['record_count']);
    $smarty->assign('page_count',           $list['page_count']);
    
    make_json_result($smarty->fetch('supplier_type_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}
/*------------------------------------------------------ */
//-- 添加、编辑供应商类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_type' || $_REQUEST['act'] == 'edit_type')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add_type';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_supplier_type' : 'edit_supplier_type';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert_type' : 'update_type');

    /* 初始化、取得供应商信息 */
    if ($is_add)
    {
        $supplier_type = array(
            'supplier_type_id'     => 0,
            'supplier_type_name'   => '',
            'supplier_type_code'   => '',
            'supplier_type_desc'   => '',
            'is_default'   		   => 0
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = intval($_GET['id']);
        $sql = "SELECT * FROM " . $os->table('supplier_type') . " WHERE supplier_type_id = '$id'";
        $supplier_type = $db->getRow($sql);
        if (empty($supplier_type))
        {
            sys_msg('供应商类型不存在');
        }
    }


    $smarty->assign('supplier_type', $supplier_type);


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加供应商类型');
    }
    else
    {
        $smarty->assign('ur_here', '编辑供应商类型');
    }
    if ($is_add)
    {
        $href = 'supplier_manage.php?act=list_type';
    }
    else
    {
        $href = 'supplier_manage.php?act=list_type&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '供应商类型列表'));
    
    assign_query_info();
    
    $smarty->display("supplier_type_info.tpl");     
}
/*------------------------------------------------------ */
//-- 提交添加、编辑供应商类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert_type' || $_REQUEST['act'] == 'update_type')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert_type';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_supplier_type' : 'edit_supplier_type';
    admin_priv($priv_str);

    /* 提交值 */
    $supplier_type = array(
        'supplier_type_id'     => intval($_POST['id']),
        'supplier_type_name'   => sub_str($_POST['supplier_type_name'], 60, false),
        'supplier_type_code'   => sub_str($_POST['supplier_type_code'], 20, false),
        'supplier_type_desc'   => strval($_POST['supplier_type_desc']),
        'is_default'           => !empty($_POST['is_default']) ? intval($_POST['is_default']) : 0    
    );

    /* 判断名称是否重复 */
    if (!$exc_type->is_only('supplier_type_name', $supplier_type['supplier_type_name'], $supplier_type['supplier_type_id']))
    {
        sys_msg('该供应商类型已存在，请您换一个名称');
    }

    /* 判断名称是否重复 */
    if (!$exc_type->is_only('supplier_type_code', $supplier_type['supplier_type_code'], $supplier_type['supplier_type_id']))
    {
        sys_msg('该供应商代码已存在，请您换一个代码');
    }
    
    /* 保存供应商类型信息 */
    if ($is_add)
    {
        $db->autoExecute($os->table('supplier_type'), $supplier_type, 'INSERT');
        $supplier_type['supplier_type_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('supplier_type'), $supplier_type, 'UPDATE', "supplier_type_id = '$supplier_type[supplier_type_id]'");
    }
	setup_is_default($supplier_type['is_default'], $supplier_type['supplier_type_id']);
    /* 记日志 */
    if ($is_add)
    {
        admin_log($supplier_type['supplier_type_name'], 'add', 'supplier_type');
    }
    else
    {
        admin_log($supplier_type['supplier_type_name'], 'edit', 'supplier_type');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'supplier_manage.php?act=add_type', 'text' => '继续添加新的供应商类型'),
            array('href' => 'supplier_manage.php?act=list_type', 'text' => '返回供应商类型列表')
        );
        sys_msg('添加供应商类型成功', 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'supplier_manage.php?act=list_type&' . list_link_postfix(), 'text' => '返回供应商类型列表')
        );
        sys_msg('编辑供应商类型成功', 0, $links);
    }	
}
/*------------------------------------------------------ */
//-- 删除供应商类型
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='remove_type'){
	
    check_authz_json('drop_supplier_type');

    $type_id = intval($_GET['id']);
    $type_name = $db->getOne("SELECT supplier_type_name FROM " . $os->table('supplier_type') . " WHERE supplier_type_id='$type_id'");    
    if($db->query("DELETE FROM " . $os->table('supplier_type') . " WHERE supplier_type_id='$type_id'")){
	    /* 记日志 */
	    admin_log($type_name, 'remove', 'supplier_type');	
	    $db->query("UPDATE " . $os->table('supplier') . " SET supplier_type=0 WHERE supplier_type='$type_id'");
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'supplier_manage.php?act=query_type&' . str_replace('act=remove_type', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;	
}
/*------------------------------------------------------ */
//-- 批量操作供应商类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch_type')
{
    /* 检查权限 */
    admin_priv('drop_supplier_type');
    
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
    {
        sys_msg('没有选择记录');
    }
    else
    {
        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
        	$sup_type_names= $db->getCol("SELECT supplier_type_name FROM " . $os->table('supplier_type') . " WHERE supplier_type_id " . db_create_in($ids));
            /* 删除记录 */
            $sql = "DELETE FROM " . $os->table('supplier_type') . " WHERE supplier_type_id " . db_create_in($ids);
            $db->query($sql);

            /* 记日志 */
            admin_log(implode(',',$sup_type_names), 'batch_remove', 'supplier_type');
			$db->query("UPDATE " . $os->table('supplier') . " SET supplier_type=0 WHERE supplier_type " . db_create_in($ids));
            /* 清除缓存 */
            clear_cache_files();

            sys_msg('批量删除供应商类型成功');
        }
    }
}

elseif($_REQUEST['act']=='list_goods'){
	
    /* 检查权限 */
    admin_priv();  
    
    if(empty($_GET['id']))
    {
    	sys_msg('供应商参数无效');
    }
    
    $smarty->assign('ur_here',      '经营商品列表');    
	$smarty->assign('action_link',  array('text' => '编辑经营商品', 'href' => 'supplier_manage.php?act=edit&id='.intval($_GET['id'])));    
	$smarty->assign('action_link2',  array('text' => '供应商列表', 'href' => 'supplier_manage.php?act=list'));   
    $smarty->assign('full_page',    1);
    
    $smarty->assign('cat_list',     cat_list(0, $cat_id));
    $smarty->assign('brand_list',   get_brand_list());
       
    $list = get_supplier_goods_list();  
    $smarty->assign('supplier_goods', $list['operate_goods']);    
    $smarty->assign('filter',        $list['filter']);
    $smarty->assign('page_count',    $list['page_count']); 
    $smarty->assign('record_count',  $list['record_count']);
    
    assign_query_info();
    $smarty->display('supplier_goods_list.tpl');		
}

elseif($_REQUEST['act']=='query_goods'){	
    $list = get_supplier_goods_list();
    $smarty->assign('supplier_goods',       $list['operate_goods']);
    $smarty->assign('filter',               $list['filter']);
    $smarty->assign('record_count',    		$list['record_count']);
    $smarty->assign('page_count',           $list['page_count']);
    
    make_json_result($smarty->fetch('supplier_goods_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}

elseif($_REQUEST['act']=='edit_goods_brief')
{
    check_authz_json('edit_supplier_goods');

    $id   = intval($_POST['id']);
    
    $name = json_str_iconv(trim($_POST['val']));
    

    if ($exc_goods->edit("goods_brief = '$name'", $id))
    {
        clear_cache_files();
        make_json_result(stripslashes($name));
    }
    else
    {
    	make_json_result('经营商品描述修改失败！');
    }
}

elseif($_REQUEST['act']=='edit_purchase_price')
{
    check_authz_json('edit_supplier_goods');

    $id       = intval($_POST['id']);
    $price    = floatval($_POST['val']);

    if ($price < 0 || $price == 0 && $_POST['val'] != "$price")
    {
        make_json_error('您输入了一个非法的商品价格。');
    }
    else
    {
        if ($exc_goods->edit("purchase_price = '$price'", $id))
        {
            clear_cache_files();
            make_json_result(number_format($price, 2, '.', ''));
        }
    }
}
/*------------------------------------------------------ */
//-- 切换是否启用
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_show')
{
    check_authz_json('edit_supplier_goods');

    $id     = intval($_POST['id']);
    $val    = intval($_POST['val']);
    $exc_goods->edit("is_open='$val'", $id);

    make_json_result($val);
}

elseif($_REQUEST['act']=='remove_goods'){
    check_authz_json('drop_supplier_goods');

    $sup_goods_id = intval($_GET['id']);  
    if($db->query("DELETE FROM " . $os->table('supplier_goods') . " WHERE supplier_goods_id='$sup_goods_id'")){
	    /* 记日志 */
	    admin_log('', 'remove', 'supplier_goods');	
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'supplier_manage.php?act=query_goods&' . str_replace('act=remove_goods', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;		
}

elseif($_REQUEST['act']=='batch_goods'){
    /* 检查权限 */
    admin_priv('drop_supplier_goods');
    
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']))
    {
        sys_msg('没有选择记录！');
    }
    else
    {
        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            /* 删除记录 */
            $sql = "DELETE FROM " . $os->table('supplier_goods') .
                    " WHERE supplier_goods_id " . db_create_in($ids);
            $db->query($sql);

            /* 记日志 */
            admin_log('', 'batch_remove', 'supplier_goods');

            /* 清除缓存 */
            clear_cache_files();

            sys_msg('批量删除经营商品成功！');
        }
    }	
}

/**
 * 获得供应商类型列表
 *
 * @access  public
 * @return  array
 */
function get_supplier_type_list(){
   $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'supplier_type_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['type_name']  = empty($_REQUEST['type_name']) ? '' : trim($_REQUEST['type_name']);
        $filter['type_code']  = empty($_REQUEST['type_code']) ? '' : trim($_REQUEST['type_code']);
      	if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['type_name'] = json_str_iconv($filter['type_name']);
            $filter['type_code'] = json_str_iconv($filter['type_code']);
        }
        $ext_sql = ' WHERE 1 ';
        if(!empty($filter['type_name'])){
        	$ext_sql .= " AND supplier_type_name LIKE '%" . mysql_like_quote($filter['type_name']) . "%' ";
        }
        if(!empty($filter['type_code'])){
        	$ext_sql .= " AND supplier_type_code LIKE '%" . mysql_like_quote($filter['type_code']) . "%' ";
        }  		

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('supplier_type') . $ext_sql;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT * FROM " . $GLOBALS['os']->table('supplier_type') . " $ext_sql ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[] = $row;
    }

    return array('type' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);		
}

/**
 * 设置默认供应商
 *
 * @access  public
 * @param   int   $val      是否默认  
 * @param   int   $type_id  供应商类型ID  
 * @return  boolean
 */
function setup_is_default($val=0, $type_id=0){
	if(!is_numeric($val) || $val <= 0) return false;
	$GLOBALS['db']->query('UPDATE ' . $GLOBALS['os']->table('supplier_type') . 
	                      ' SET is_default=0 WHERE supplier_type_id <> ' . 
	                      intval($type_id));
    return true;
}

/**
 * 获取供应商的经营商品
 *
 * @access  public
 * @param   int    $supplier_id 供应商ID  
 * @return  array
 */
function get_supplier_goods($supplier_id)
{
    $sql = "SELECT sg.goods_id, CONCAT(g.goods_name, ' -- [货号 ', g.goods_sn, ', 价格 ',sg.purchase_price ,']') " . 
           " AS goods_name FROM " . $GLOBALS['os']->table('supplier_goods') . " AS sg, " . $GLOBALS['os']->table('goods') . 
           " AS g WHERE sg.supplier_id = '$supplier_id' AND sg.goods_id = g.goods_id ";
    if ($supplier_id == 0)
    {
        $sql .= " AND sg.admin_id = '$_SESSION[admin_id]'";
    }
    $row = $GLOBALS['db']->getAll($sql);

    return $row;
}

/**
 * 设置供应商的经营商品
 *
 * @access  public
 * @param   int    $supplier_id 供应商ID  
 * @return  void
 */
function handle_supplier_goods($supplier_id)
{
    $sql = "UPDATE " . $GLOBALS['os']->table('supplier_goods') . " SET " .
            " supplier_id = '$supplier_id' " .
            " WHERE supplier_id=0 AND admin_id = '$_SESSION[admin_id]'";
    $GLOBALS['db']->query($sql);
} 

function get_supplier_goods_list(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'supplier_goods_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['id']               = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
        $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        $filter['brand_id']         = empty($_REQUEST['brand_id']) ? 0 : intval($_REQUEST['brand_id']);
        $filter['is_open']           = (!is_numeric($_REQUEST['is_open']) || $_REQUEST['is_open']<0) ? -1 : intval($_REQUEST['is_open']);
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        
        $ext_sql = " WHERE sg.supplier_id='$filter[id]'";
		$ext_sql .= $filter['cat_id'] > 0 ? " AND " . get_children($filter['cat_id']) : '';
		
        /* 品牌 */
        if ($filter['brand_id'])
        {
            $ext_sql .= " AND g.brand_id='$filter[brand_id]'";
        }  
        
        if ($filter['is_open']>=0)
        {
            $ext_sql .= " AND sg.is_open='$filter[is_open]'";
        } 
        
        /* 关键字 */
        if (!empty($filter['keyword']))
        { 
			$filter['keyword'] = urldecode($filter['keyword']);
            $ext_sql .= " AND (g.goods_sn LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }	

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('supplier_goods') . " sg LEFT JOIN " . 
               $GLOBALS['os']->table('goods') . " g ON sg.goods_id=g.goods_id " . $ext_sql;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT g.goods_id,g.goods_name,g.goods_sn,sg.supplier_goods_id,sg.purchase_price,sg.goods_brief," . 
               " sg.is_open FROM " . $GLOBALS['os']->table('supplier_goods') . " sg JOIN " . $GLOBALS['os']->table('goods') . 
               " g ON sg.goods_id=g.goods_id " . $ext_sql . " ORDER BY $filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
    	$row['short_goods_name']  = sub_str($row['goods_name'],20);
    	$row['short_goods_brief'] = sub_str($row['goods_brief'],30);
        $arr[] = $row;
    }

    return array('operate_goods' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}
?>